/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:
 * Date: 2024-11-08
 * Time: 19:33
 */
public class ReplaceString {

    public static void main(String[] args) {
        String originalString = "hello world, hello moon, hello sun";
        String toReplace = "hello";
        String replacement = "hi";

        int count = replace(originalString, toReplace, replacement);
        System.out.println("Original String: " + originalString);
        System.out.println("After replacement: " + originalString);
        System.out.println("Replacements made: " + count);
    }

    public static int replace(String str, String target, String replacement) {
        if (str == null || target == null || replacement == null) {
            throw new IllegalArgumentException("Input strings cannot be null");
        }

        int count = 0;
        int start = 0;
        int len = target.length();
        int pos;

        while ((pos = str.indexOf(target, start)) != -1) {
            str = str.substring(0, pos) + replacement + str.substring(pos + len);
            start = pos + replacement.length();
            count++;
        }

        System.out.println("Modified String: " + str);
        return count;
    }
}